package com.rem.web;

import com.rem.utils.CookieUtils;
import jdk.internal.org.objectweb.asm.tree.analysis.Value;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author remembrance
 * @version 1.0
 * @date 2021/10/11 10:57
 */
public class CookieServlet extends BaseServlet{
    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie1 = new Cookie("key1","value1");
        Cookie cookie2 = new Cookie("key2","value2");
        Cookie cookie3 = new Cookie("key3","value3");
        Cookie cookie4 = new Cookie("key4","value4");
        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
        resp.addCookie(cookie3);
        resp.addCookie(cookie4);
        resp.getWriter().write("cookie创建成功");
    }

    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        CookieUtils.findCookie("key1",cookies);
    }

    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        Cookie cookie = CookieUtils.findCookie("key1",cookies);
        if (cookie != null){
            cookie.setValue("newValue1");
            resp.addCookie(cookie);
            resp.getWriter().write("修改后的值是"+ cookie.getValue());
        }
    }

    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       Cookie cookie = new Cookie("key2", "value2");
       cookie.setMaxAge(-1);
       resp.addCookie(cookie);
    }

    protected void deleteCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = CookieUtils.findCookie("key3", req.getCookies());
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }

    protected void aHourCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = CookieUtils.findCookie("key4", req.getCookies());
        cookie.setMaxAge(3600);
        resp.addCookie(cookie);
    }
}
